#include "ADUCar.h"
#include "../GameUtils/ADUConstants.h"

ADUCar::ADUCar() {
	carState = ADUCarStateMoving;
}

ADUCar* ADUCar::CreateCarBYFileName(const char* filename) {
	ADUCar* car = new ADUCar();
	if (car && car->initWithFile(filename)) {
		car->autorelease();
		return car;
	}
	CC_SAFE_DELETE(car);
	return NULL;
}

void ADUCar::setState(int state) {
	carState = state;
}
int ADUCar::getState() {
	return carState;
}

void ADUCar::setRoad(ADURoad *road) {
	mRoad = road;
	_meta = mRoad->getMeta();
}

void ADUCar::ditermine(CCAcceleration* pAccelerationValue) {
	double delta = 0;
	double deltaX = 0;
	double newposX = 0;
	double angle = 0;
	int sign;
	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();
	CCSize carSize = this->getContentSize();
	delta = pAccelerationValue->x - ADUBalancedState;
	angle = delta * 30;
	this->setRotation(angle);
	deltaX = 20 * (pAccelerationValue->x - ADUBalancedState);

	sign = delta < 0 ? -1 : 1;

	newposX = this->getPositionX() + deltaX;
	CCPoint tileCoord = this->tileCoordForPosition(
			ccp(newposX + sign * carSize.width / 4, this->getPositionY()));
	int tileGid = _meta->tileGIDAt(tileCoord);
	if (tileGid) {
		CCDictionary *properties = mRoad->propertiesForGID(tileGid);
		if (properties) {
			CCString *collision = new CCString();
			*collision = *properties->valueForKey(std::string("Collidable"));
			if (collision && (collision->compare("True") == 0)) {
				return;
			}
		}
	}
	this->setPositionX(newposX);
}

CCPoint ADUCar::tileCoordForPosition(CCPoint position) {
	int x = position.x / mRoad->getTileSize().width;
	int y = ((mRoad->getMapSize().height * mRoad->getTileSize().height)
			- position.y) / mRoad->getTileSize().height;
	return ccp(x, y);
}

void ADUCar::jump() {
	if (carState == ADUCarStateJumping)
		return;
	carState = ADUCarStateJumping;
	CCScaleTo* scaleup = CCScaleTo::create(1.0f, 1.3f);
	CCScaleTo* scaledown = CCScaleTo::create(1.0f, 1.0f);
	CCFiniteTimeAction* actionJumpFinished = CCCallFuncN::create(this,
			callfuncN_selector(ADUCar::carJumpFinished));
	CCSequence* jump = CCSequence::create(scaleup, scaledown,
			actionJumpFinished, NULL);
	this->runAction(jump);
}

void ADUCar::carJumpFinished(CCNode* node) {
	carState = ADUCarStateMoving;
}
